package com.huanxing.cloud.security.config;

import com.huanxing.cloud.security.exception.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.DefaultThrowableAnalyzer;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.web.util.ThrowableAnalyzer;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestMethodNotSupportedException;

/**
 * SpringSecurity OAuth2 异常翻译器，统一捕获授权时异常信息处理
 * https://blog.csdn.net/CSDN877425287/article/details/120579509
 *
 * @author lijx
 * @version 1.0
 * @date 2022/5/16 23:01
 */
@Slf4j
@Component
public class HxAuth2ResponseExceptionTranslator implements WebResponseExceptionTranslator {

  private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();

  @Override
  public ResponseEntity translate(Exception e) throws Exception {

    Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
    Exception ase; // 异常栈获取 OAuth2Exception 异常

    ase =
        (AuthenticationException)
            throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);
    if (ase != null) {
      return handleOAuth2Exception(new UnauthorizedException(e.getMessage(), e));
    }

    ase =
        (AccessDeniedException)
            throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);
    if (ase != null) {
      return handleOAuth2Exception(new ForbiddenException(ase.getMessage(), ase));
    }
    ase =
        (InvalidGrantException)
            throwableAnalyzer.getFirstThrowableOfType(InvalidGrantException.class, causeChain);
    if (ase != null) {
      return handleOAuth2Exception(new InvalidException(ase.getMessage(), ase));
    }

    ase =
        (HttpRequestMethodNotSupportedException)
            throwableAnalyzer.getFirstThrowableOfType(
                HttpRequestMethodNotSupportedException.class, causeChain);
    if (ase != null) {
      return handleOAuth2Exception(new MethodNotAllowedException(ase.getMessage(), ase));
    }

    ase =
        (InvalidTokenException)
            throwableAnalyzer.getFirstThrowableOfType(InvalidTokenException.class, causeChain);
    if (ase != null) {
      return handleOAuth2Exception(
          new com.huanxing.cloud.security.exception.InvalidTokenException(ase.getMessage(), ase));
    }

    ase =
        (OAuth2Exception)
            throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain);

    if (ase != null) {
      return handleOAuth2Exception((OAuth2Exception) ase);
    }

    // 不包含上述异常则服务器内部错误
    return handleOAuth2Exception(new ServerErrorException(HttpStatus.OK.getReasonPhrase(), e));
  }

  private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) {

    int status = e.getHttpErrorCode();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cache-Control", "no-store");
    headers.set("Pragma", "no-cache");
    if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
      headers.set(
          "WWW-Authenticate",
          String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
    }

    return new ResponseEntity<>(
        new HxExtendOauth2Exception(e.getMessage(), e.getOAuth2ErrorCode()),
        headers,
        HttpStatus.valueOf(status));
  }
}
